package com.aaa.marketresearch.webclient.gwt.admin.widget;

import com.aaa.marketresearch.webclient.gwt.admin.AdminRequester;
import com.aaa.marketresearch.webclient.gwt.domain.Goods;
import com.aaa.marketresearch.webclient.gwt.util.ConsoleLog;
import com.aaa.marketresearch.webclient.gwt.util.Responder;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.HasKeyboardSelectionPolicy;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;

import java.util.ArrayList;
import java.util.List;


/**
 * @author Nail
 */
public class GoodsTable extends Composite {

    interface GoodsTableUiBinder extends UiBinder<Widget, GoodsTable> { }
    private static GoodsTableUiBinder uiBinder = GWT.create(GoodsTableUiBinder.class);

    private static GoodsTable instance = null;

    public static GoodsTable getInstance() {
        if (instance == null) {
            instance = new GoodsTable();
        }
        return instance;
    }

    @UiField
    Button addGoods;

    @UiField
    FlowPanel goodsTable;

    @UiField
    Button saveGoods;

    @UiField
    TextBox barcode;

    @UiField
    TextBox name;

    @UiField
    TextArea description;

    @UiField
    ListBox countable;

    @UiField
    ListBox units;
/*
    @UiField
    TextBox capacity;

    @UiField
    TextBox demand;
*/
    private CellTable table;
    private Goods selectedGoods;
    private List<Goods> goodsData;

    public GoodsTable() {
        // initialize
        initWidget(uiBinder.createAndBindUi(this));

        table = new CellTable();

        table.setKeyboardSelectionPolicy(HasKeyboardSelectionPolicy.KeyboardSelectionPolicy.ENABLED);

        // Add a text column to show the name.
        TextColumn<Goods> nameColumn = new TextColumn<Goods>() {
            @Override
            public String getValue(Goods object) {
                return object.getName();
            }
        };

        table.addColumn(nameColumn, "Name");

        // Add a text column to show the email.
        TextColumn<Goods> barcodeColumn = new TextColumn<Goods>() {
            @Override
            public String getValue(Goods object) {
                return object.getBarcode().toString();
            }
        };
        table.addColumn(barcodeColumn, "Barcode");

        // Add a text column to show the role.
        TextColumn<Goods> demandColumn = new TextColumn<Goods>() {
            @Override
            public String getValue(Goods object) {
                return object.getDemand().toString();
            }
        };
        table.addColumn(demandColumn, "Demand");

        // Add a selection model to handle user selection.
        final SingleSelectionModel<Goods> selectionModel = new SingleSelectionModel<Goods>();
        table.setSelectionModel(selectionModel);
        selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
            public void onSelectionChange(SelectionChangeEvent event) {
                Goods selected = selectionModel.getSelectedObject();
                if (selected != null) {
                    GoodsTable.this.setActiveGoods(selected);
                }
            }
        });

        this.goodsTable.add(table);

        this.saveGoods.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                GoodsTable.this.saveGoods();
            }
        });

        this.addGoods.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                GoodsTable.this.addNewGoods();
            }
        });
    }

    public void loadData() {
        AdminRequester request = new AdminRequester();
        request.addResponder(new Responder() {
            @Override
            public void handleGetResponse(String content) {
                GoodsTable.this.goodsUpdated(content);
            }
        });
        request.getGoods(0);
    }

    private void goodsUpdated(String content) {
        JSONArray data = (JSONArray) JSONParser.parseLenient(content);
        int n = data.size();

        this.goodsData = new ArrayList<Goods>(n);

        for (int i = 0; i < n; i++) {
            JSONObject obj = data.get(i).isObject();
            Goods goods = new Goods(obj);
            this.goodsData.add(goods);
        }

        table.setRowCount(this.goodsData.size(), true);
        table.setRowData(0, this.goodsData);
    }

    private void setActiveGoods(Goods goods) {
        this.selectedGoods = goods;
        this.name.setText(goods.getName());
        this.barcode.setText(goods.getBarcode().toString());
        this.description.setText(goods.getDescription());
        {
            int n = this.countable.getItemCount();
            for(int i = 0; i < n; i++){
                String value = this.countable.getValue(i);
                Boolean countable = goods.getCountable();
                if (value.equalsIgnoreCase("YES") && countable) {
                    this.countable.setSelectedIndex(i);
                    break;
                } else if (value.equalsIgnoreCase("NO") && !countable) {
                    this.countable.setSelectedIndex(i);
                    break;
                }
            }
        }
        {
            int n = this.units.getItemCount();
            for(int i = 0; i < n; i++){
                String value = this.units.getValue(i);
                if (value.equalsIgnoreCase(goods.getUnits())) {
                    this.units.setSelectedIndex(i);
                    break;
                }
            }
        }
        /*
        this.capacity.setText(goods.getCapacity().toString());
        this.demand.setText(goods.getDemand().toString());
        */
    }


    private void saveGoods() {
        if (this.selectedGoods != null) {
            {
                Long barcodeValue = 0L;
                try {
                    barcodeValue = Long.parseLong(this.barcode.getText());
                } catch (NumberFormatException e) {
                    Window.alert("Barcode incorrect value");
                    return;
                }
                this.selectedGoods.setBarcode(barcodeValue);
            }
            this.selectedGoods.setName(this.name.getText());
            this.selectedGoods.setDescription(this.description.getText());

            String countableValue = this.countable.getValue(this.countable.getSelectedIndex());
            if (countableValue.equalsIgnoreCase("NO")) {
                this.selectedGoods.setCountable(false);
            } else {
                this.selectedGoods.setCountable(true);
            }

            this.selectedGoods.setUnits(this.units.getValue(this.units.getSelectedIndex()));

            {
                Double capacityValue = 0.0;
                /*
                try {
                    capacityValue = Double.parseDouble(this.capacity.getText());
                } catch (NumberFormatException e) {
                    Window.alert("Capacity incorrect value");
                    return;
                }
                */
                this.selectedGoods.setCapacity(capacityValue);

            }

            {
                Integer demandValue = 0;
                /*
                try {
                    demandValue = Integer.parseInt(this.demand.getText());
                } catch (NumberFormatException e) {
                    Window.alert("Demand incorrect value");
                    return;
                }
                */
                this.selectedGoods.setDemand(demandValue);
            }

            AdminRequester goodsRequest = new AdminRequester();
            goodsRequest.addResponder(new Responder() {
                @Override
                public void handleGetResponse(String content) {
                    ConsoleLog.getInstance().info("saved Goods");
                    table.setRowData(0, GoodsTable.this.goodsData);
                }
            });
            goodsRequest.saveGoods(this.selectedGoods);
        }
    }

    private void addNewGoods() {
        Goods goods = new Goods();
        this.goodsData.add(0, goods);

        table.setRowCount(this.goodsData.size(), true);
        table.setRowData(0, this.goodsData);
    }

}
